package com.zxbg.service.impl.systemtoolsServiceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxbg.dao.AuthDao;
import com.zxbg.dao.RoleDao;
import com.zxbg.domain.Auth;
import com.zxbg.domain.Employee;
import com.zxbg.domain.Role;
import com.zxbg.domain.SystemtoolsLeftMenu;
import com.zxbg.service.systemtoolsService.FunctionalAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FunctionalAuthorityServiceImpl implements FunctionalAuthorityService {
    @Autowired
    AuthDao authDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public List<Auth> getAuth(List<String> menu_codes) {
        List<Auth> authList = new ArrayList<>();
        if(menu_codes != null && menu_codes.size() > 0) {
            for (String menu_code : menu_codes) {
                List<Auth> temp = authDao.getAuthByMenuCode(menu_code);
                if(temp != null) {
                    authList.addAll(temp);
                }
            }
        }
        return authList;
    }

    @Override
    public boolean setAuth(List<SystemtoolsLeftMenu> systemtoolsLeftMenuList, List<Auth> authList, String role_code, Integer tenant_id) {
        if(systemtoolsLeftMenuList.size() == 0) {
            roleDao.setAuthByRoleCode(role_code, null, tenant_id);
            return true;
        }
        String menuString = "";
        String authorityString = "";
        for (int i = 0; i < systemtoolsLeftMenuList.size(); i++) {
            String jsonObject = JSON.toJSONString(systemtoolsLeftMenuList.get(i));
            SystemtoolsLeftMenu systemtoolsLeftMenu = JSONObject.parseObject(jsonObject, SystemtoolsLeftMenu.class);
            String tempMenuCode = systemtoolsLeftMenu.getMenu_code();
            List<String> currentAllAuthId = authDao.getAuthIdByMenuCode(tempMenuCode);
            if(currentAllAuthId != null) {
                for (int j = 0; j < authList.size(); j++) {
                    jsonObject = JSON.toJSONString(authList.get(j));
                    Auth auth = JSONObject.parseObject(jsonObject, Auth.class);
                    if(currentAllAuthId.contains(auth.getAuth_id())) {
                        authorityString = authorityString.equals("") ? auth.getAuth_id() : authorityString + "," + auth.getAuth_id();
                    }
                }
            }
            menuString = menuString.equals("") ? tempMenuCode : menuString + "," + tempMenuCode;
        }
        if(authorityString.equals("")) {
            roleDao.setAuthByRoleCode(role_code, menuString, tenant_id);
        } else {
            roleDao.setAuthByRoleCode(role_code, menuString + " & " + authorityString, tenant_id);
        }
        return true;
    }
}
